﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorldServer.Helpers;
using AionCxxLibrary.Utilities;
using AionCxxLibrary.Packets;

namespace WorldServer.Models
{
    public class LevelInstance
    {
        /// <summary>
        /// List (sorted by AionID) of all objects in this instance.
        /// </summary>
        Dictionary<int, AionObject> Objects = new Dictionary<int, AionObject>();

        public readonly int GUID;
        public readonly ushort ChannelID;
        public readonly int WorldID;

        public LevelInstance(int guid, int worldid, ushort channel)
        {
            GUID = guid;
            WorldID = worldid;
            ChannelID = channel;
        }

        public void RecalculateNearbyObjects(AionObject obj)
        {
            DateTime start = DateTime.Now;
            if (obj.NearbyObjects.Processing)
                return;
            lock (obj.NearbyObjects)
            {
                obj.NearbyObjects.Processing = true;
                foreach (AionObject aobj in Objects.Values)
                {
                    if (aobj is Character && !(aobj as Character).Connected && obj.NearbyObjects.Contains(aobj))
                    {
                        obj.NearbyObjects.Remove(aobj);
                        continue;
                    }
                    double distance = MathHelper.GetDistance(obj.Position.x, obj.Position.y, obj.Position.z, aobj.Position.x, aobj.Position.y, aobj.Position.z);
                    if (obj.NearbyObjects.Contains<AionObject>(aobj) && distance > 20)
                    {
                        obj.NearbyObjects.Remove(aobj);
                        if(!aobj.NearbyObjects.Processing)
                            aobj.NearbyObjects.Remove(obj);
                    }
                    else if (!obj.NearbyObjects.Contains<AionObject>(aobj) && distance < 20)
                    {
                        obj.NearbyObjects.Add(aobj);
                        if(!aobj.NearbyObjects.Processing)
                            aobj.NearbyObjects.Add(obj);
                    }
                }
                obj.NearbyObjects.Processing = false;
            }
            TimeSpan time = (DateTime.Now - start);
            Log.Debug("NearbyObjects for " + obj.GetGUID() + " - " + time.TotalMilliseconds + " ms - " + obj.NearbyObjects.Count + " objects.");
        }

        public void Register(AionObject obj)
        {
            if(Objects.ContainsKey(obj.GetGUID()))
            {
                Log.Warn("Trying to register an already registered AionObject " + obj.GetGUID() + " in LevelInstance " + WorldID + "/" + GUID);
                return;
            }
            Objects.Add(obj.GetGUID(), obj);
        }

        public void Unregister(int aionId)
        {
            if(!Objects.ContainsKey(aionId))
            {
                Log.Warn("Trying to unregister an unexisting object " + aionId);
                return;
            }
            Objects.Remove(aionId);
        }

    }

    /// <summary>
    /// This class represents a Level-aware list of AionObjects.
    /// Generally we use it for each AionObject to register all other objects near this object.
    /// </summary>
    public class SeeList : EventAwareList<AionObject>
    {
        AionObject owner;
        public bool Processing = false;

        public SeeList(AionObject obj)
        {
            owner = obj;
            BeforeAdd += new EventAwareListBeforeAddEvent<AionObject>(ObjectList_BeforeAdd);
            OnAdd += new EventAwareListAddEvent<AionObject>(ObjectList_OnAdd);
            OnRemove += new EventAwareListRemoveEvent<AionObject>(SeeList_OnRemove);
        }

        void SeeList_OnRemove(object sender, EventArgs<AionObject> e)
        {
            owner.UnseeObject(e.Value);
        }

        void ObjectList_OnAdd(object sender, EventArgs<AionObject> e)
        {
            owner.SeeObject(e.Value);
        }

        bool ObjectList_BeforeAdd(object sender, EventArgs<AionObject> e)
        {
            if (e.Value.GetGUID() == owner.GetGUID())
                return false;
            return true;
        }

        public void BroadcastPacket(AionServerPacket pkt, bool toSelf)
        {
            lock (this)
            {
                foreach(AionObject o in this)
                {
                    if (o is Character)
                    {
                        Character c = o as Character;
                        c.SendPacket(pkt);
                    }
                }
                if (toSelf && owner is Character)
                {
                    (owner as Character).SendPacket(pkt);
                }
            }
        }

    }

}
